<?php
// +----------------------------------------------------------------------
// | 商家模块
// +----------------------------------------------------------------------

namespace app\mall\admin;

use app\admin\controller\Admin;
use app\common\builder\ZBuilder;
use app\mall\model\Qrcode as QrcodeModel;
use app\mall\model\Merch as MerchModel;
use app\mall\model\Child as ChildModel;
use qrcode\Qrcode as QrcodeTool;
use util\Tree;
use util\File;
use util\PHPZip;
/**
 * 二维码控制器
 * @package app\mall\admin
 */
class Qrcode extends Admin
{
    /**
     * 二维码列表
     */
    public function index()
    {
		$this->success('功能研发中…');
        // 查询
        $map = $this->getMap();
		$order = $this->getOrder('sort,id desc');
		
        // 数据列表
        $data_list = QrcodeModel::where($map)->order($order)->paginate(config('paginate'));
		foreach ($data_list as $key => $value){
			$data_list[$key]['qrcode'] = '<i class="fa fa-fw fa-qrcode"></i>';
			if ($value['mch_id'] > 0){
				$merch = MerchModel::getInfo($value['mch_id']);
				if ($merch) $data_list[$key]['merch'] = $merch['short_name'];
			}
			
			if ($value['sub_id'] > 0){
				$child = ChildModel::getInfo($value['sub_id']);
				if ($child) $data_list[$key]['child'] = $child['name'];
			}
		}
		// 批量新增
		$btnAdd = [
			'title' => '批量新增',
			'icon'  => 'fa fa-plus-circle',
			'class' => 'btn btn-primary',
			'href'  => url('addall')
		];
		// 导出按钮
		$btnExport = [
			'title' => '打包二维码',
			'icon'  => 'fa fa-fw fa-save',
			'class' => 'btn btn-default js-get',
			'href'  => url('export')
		];
		$merch_list = MerchModel::getColumn();
		$merch_list[0] = '未绑定';
        // 使用ZBuilder快速创建数据表格
        return ZBuilder::make('table')
            ->setSearch(['id' => '二维码ID', 'mch_id' => '商家ID', 'sub_id' => '终端ID']) // 设置搜索框
            ->addColumns([ // 批量添加数据列
               ['id', 'ID'],
			   ['cid', '分类', 'status', '', CategoryModel::getColumn()],
               ['mch_id', '商家', 'callback', function($value, $data){
                   return isset($data['merch']) ? $data['merch'] : '未绑定';
               }, '__data__'],
			   ['sub_id', '终端', 'callback', function($value, $data){
			       return isset($data['child']) ? $data['child'] : '未绑定';
			   }, '__data__'],
			   ['qrcode', '收款码', 'link', url('qrcode/qrcode', ['id'=>'__id__']), '_blank', 'pop', '收款码'],
               ['view', '扫码次数', 'text'],
               ['status', '状态', 'switch'],
               ['right_button', '操作', 'btn']
            ])
            ->addTopButtons('add,enable,disable') // 批量添加顶部按钮
			->addTopButton('custom', $btnAdd) // 添加批量新增
			->addTopButton('custom', $btnExport) // 添加导出按钮
            ->addRightButton('edit') // 添加右侧按钮
            ->addRightButton('delete', ['data-tips' => '删除二维码无法恢复！']) // 添加右侧按钮
			->addFilterList('cid', CategoryModel::getColumn())
			->addFilterList('mch_id', $merch_list)
            ->setRowList($data_list) // 设置表格数据
            ->fetch(); // 渲染模板
    }

    /**
     * 新增二维码
     */
    public function add()
    {
        // 保存数据
        if ($this->request->isPost()) {
            // 表单数据
            $data = $this->request->post();

            // 验证
            $result = $this->validate($data, 'Qrcode');
            if(true !== $result) $this->error($result);
			if ($data['sub_id'] > 0){
				$added = QrcodeModel::where('sub_id', $data['sub_id'])->find();
				if($added) $this->error('该终端已绑定二维码');
			} 
            if ($qrcode = QrcodeModel::create($data)) {
                // 记录行为
                action_log('qrcode_add', 'merch_qrcode', $qrcode->id, UID, '二维码ID'.$qrcode->id);
				// 同步终端信息
				if ($data['sub_id'] > 0) ChildModel::where('id', $data['sub_id'])->update(['code' => $qrcode->id]);
                $this->success('新增成功', 'index');
            } else {
                $this->error('新增失败');
            }
        }
		$category_list = CategoryModel::getColumn();
		$merch_list = MerchModel::getColumn();
        // 显示添加页面
        return ZBuilder::make('form')
            ->addFormItems([
                ['linkage', 'cid', '选择分类', '', $category_list, '', url('get_merch'), 'mch_id'],
				['linkage', 'mch_id', '选择商家', '', $merch_list, '', url('get_child'), 'sub_id'],
                ['select', 'sub_id', '选择终端',],
				['radio', 'status', '立即启用', '', ['否', '是'], 1],
                ['text:8', 'sort', '排序', '', 100],
            ])
            ->fetch();
    }

    /**
     * 编辑二维码
     */
    public function edit($id = '')
    {
        if ($id === 0) $this->error('参数错误');
		// 获取数据
		$info = QrcodeModel::where('id', $id)->find();
		
        // 保存数据
        if ($this->request->isPost()) {
            $data = $this->request->post();

            // 验证
            $result = $this->validate($data, 'Qrcode');
            // 验证失败 输出错误信息
            if(true !== $result) $this->error($result);
			if ($data['sub_id'] > 0){
				$added = QrcodeModel::where('sub_id', $data['sub_id'])->where('id', '<>', $id)->find();
				if($added) $this->error('该终端已绑定二维码');
			} 
            if (QrcodeModel::update($data)) {
                // 记录行为
                action_log('qrcode_edit', 'merch_qrcode', $id, UID, '二维码ID'.$id);
				cache('merch_qrcode_info_'. $id, null);
				// 同步终端信息
				if ($info['sub_id'] != $data['sub_id']) ChildModel::where('id', $info['sub_id'])->update(['code' => 0]);
				if ($data['sub_id'] > 0) ChildModel::where('id', $data['sub_id'])->update(['code' => $id]);
                return $this->success('编辑成功', 'index');
            } else {
                return $this->error('编辑失败');
            }
        }
		
        
		$category_list = CategoryModel::getColumn();
		$merch_list = MerchModel::getColumn($info['cid']);
		$child_list = [];
		if ($info['mch_id'] > 0) $child_list = ChildModel::getColumn($info['mch_id']);
		
        // 显示编辑页面
        return ZBuilder::make('form')
            ->addFormItems([
                ['hidden', 'id'],
                ['linkage', 'cid', '选择分类', '', $category_list, '', url('get_merch'), 'mch_id'],
                ['linkage', 'mch_id', '选择商家', '', $merch_list, '', url('get_child'), 'sub_id'],
                ['select', 'sub_id', '选择终端', '', $child_list],
                ['radio', 'status', '立即启用', '', ['否', '是']],
                ['text:8', 'sort', '排序'],
            ])
            ->setFormData($info)
            ->fetch();
    }
    // 二维码图片
	public function qrcode($id = 0)
	{	
		//生成路径
		$img = real_url('merch/qrcode/getimg', ['id' => $id]);
		$table_data = [
		    ['<img src="'.$img.'" style="margin:20px auto; display:block; width:240px">'],
		    ['<span style="text-align:center; width:100%; display:block;">二维码ID：'.$id.'</span>'],
		];
		
		return ZBuilder::make('form')
		    ->setPageTitle('查看二维码') // 设置页面标题
		    ->addFormItems([ // 批量添加表单项
		        ['complexTable', 'qrcode', '二维码', $table_data]
		    ])
			->hideBtn(['submit', 'back'])
		    ->fetch();
	}
	/**
	 * 打包二维码
	 * @return mixed
	 */
	public function export()
	{
	    $ids = $this->request->isPost() ? input('post.ids/a') : input('param.ids');
		if (!is_array($ids)) $ids = explode(',', $ids);
		if (!$ids) $this->error('请选择二维码');
		// 模块导出目录
		$qrcode_dir = root_path(). 'export/qrcode';
		
		// 删除旧的导出数据
		if (is_dir($qrcode_dir)) {
		    File::del_dir($qrcode_dir);
		}
		mkdir($qrcode_dir, 0777, true);
		foreach ($ids as $id){
			$file = public_path().'uploads/qrcode/'.$id.'.png';
			if (is_file($file)) {
				copy($file, $qrcode_dir.'/code_'.$id.'.png');
			} else {
				$info = QrcodeModel::find($id);
				if (!$info) continue;
				//生成路径
				$url = real_url('mall/source/query', ['id' => $id]);
				$qrcode = new QrcodeTool;
				$qrcode->save($url, 14, 0, 'uploads/qrcode/', $id);
				copy($file, $qrcode_dir.'/code_'.$id.'.png');
			}
		}
		// 打包下载
		$archive = new PHPZip;
		$url = $archive->ZipAndDownload($qrcode_dir, '二维码');
		$this->success('打包成功', $url);
	}
	/**
	 * 批量新增二维码
	 */
	public function addall()
	{
	    // 保存数据
	    if ($this->request->isPost()) {
	        // 表单数据
	        $data = $this->request->post();
			
			if (!$data['cid']){
				$this->error('请选择分类类型');
			}
			if ($data['numbers'] <= 0 || $data['numbers'] > 100){
				$this->error('数量必须介于1-100之间');
			}
			$data_list = [];
			for ($i = 0; $i < $data['numbers']; $i++){
				$data_list[$i] = ['cid' => $data['cid']];
			}
			$qrcode = new QrcodeModel;
	        if ($qrcode->saveAll($data_list)) {
	            $this->success('新增成功', 'index');
	        } else {
	            $this->error('新增失败');
	        }
	    }
		$category_list = CategoryModel::getColumn();
	    // 显示添加页面
	    return ZBuilder::make('form')
	        ->addFormItems([
	            ['select:8', 'cid', '选择分类', '', $category_list],
	            ['text:8', 'numbers', '新增数量', '', 10],
	        ])
	        ->fetch();
	}
	// 根据分类获取商家
	public function get_merch($cid = 0)
	{
		$merch = MerchModel::getColumn($cid);
		
		if($cid == 0 || !$merch){
			$arr['code'] = '0'; //判断状态
			$arr['msg'] = '未查找到数据'; //回传信息
			$arr['list'] = [];
		}else{
			$arr['code'] = '1'; //判断状态
			$arr['msg'] = '请求成功'; //回传信息
			$arr['list'] = []; //数据
			foreach ($merch as $key => $value){
				$arr['list'][] = ['key' => $key, 'value' => $value];
			}
		}
		return json($arr);
	}

	// 根据商家获取终端
	public function get_child($mch_id = '')
	{
		$child = ChildModel::getColumn($mch_id, true);
		
		if($mch_id == 0 || !$child){
			$arr['code'] = '0'; //判断状态
			$arr['msg'] = '未查找到数据'; //回传信息
			$arr['list'] = [];
		}else{
			$arr['code'] = '1'; //判断状态
			$arr['msg'] = '请求成功'; //回传信息
			$arr['list'] = []; //数据
			foreach ($child as $key => $value){
				$arr['list'][] = ['key' => $key, 'value' => $value];
			}
		}
		return json($arr);
	}
    /**
     * 删除二维码
     * @param null $ids 二维码id
     */
    public function delete($record = [])
    {
		return $this->setStatus('delete');
    }

    /**
     * 启用二维码
     * @param array $record 行为日志
     */
    public function enable($record = [])
    {
        return $this->setStatus('enable');
    }

    /**
     * 禁用二维码
     * @param array $record 行为日志
     */
    public function disable($record = [])
    {
        return $this->setStatus('disable');
    }

    /**
     * 设置二维码状态：删除、禁用、启用
     * @param string $type 二维码：enable/disable
     * @return mixed
     */
    public function setStatus($type = '', $record = [])
    {
        $ids           = $this->request->isPost() ? input('post.ids/a') : input('param.ids/a');
		// 清除缓存
		foreach ($ids as $id){
			cache('merch_qrcode_info_'. $id, null);
		}
        $column_delete = is_array($ids) ? '' : $ids;
        $column_names  = QrcodeModel::where('id', 'in', $ids)->column('id');
		if ($type == 'delete') {
			$childs = QrcodeModel::where('id', 'in', $ids)->column('sub_id');
			// 同步终端信息
			ChildModel::where('id', 'in', $childs)->update(['code' => 0]);
		}
        return parent::setStatus($type, ['qrcode_'.$type, 'merch_qrcode', $column_delete, UID, implode('、', $column_names)]);
    }

    /**
     * 快速编辑
     * @param array $record 行为日志
     * @return mixed
     */
    public function quickEdit($record = [])
    {
        $id      = input('post.pk', '');
        $field   = input('post.name', '');
        $value   = input('post.value', '');
		cache('merch_qrcode_info_'. $id, null);
        $column  = QrcodeModel::where('id', $id)->value($field);
        $details = '字段(' . $field . ')，原值(' . $column . ')，新值：(' . $value . ')';
        return parent::quickEdit(['qrcode_edit', 'merch_qrcode', $id, UID, $details]);
    }
}